#切换目录
cd $(cd "$(dirname "$0")" && pwd)

#输出帮助文档
function printHelp() {
    echo "-clear            清空全部设置"
    echo "-Path             orderer 与 cryptogen 命令位置"
    echo "-channelID        通道名称"
    echo "-crypto_config    crypto-config.yaml 文件位置"
    echo "-configtx         configtx.yaml 文件位置"
    echo "-orderer          orderer.yaml 文件位置"
    echo "-ports_config     配置文件位置"
    echo "-port             order 节点端口"
    echo "-h                打印此帮助界面"
    echo
    echo
    echo "当前各属性默认参数"
    echo "-Path             ${path}"
    echo "-channelID        ${channelID}"
    echo "-crypto_config    ${crypto_config}"
    echo "-configtx         ${configtx}"
    echo "-orderer          ${orderer}"
    echo "-ports_config     ${ports_config}"
    echo "-port             ${port}"
}

#替换指定文件内容
function replaceContent() {
    sed -i "s/$2/$3/g" $1
}

#检查返回值
function checkRet() {
    if [ $1 != "0" ]; then
        echo
        echo "程序异常结束"
        exit 1
    fi
}

#判断文件是否存在
function checkFile() {
    if [ ! -f $1 ]; then
        echo 文件 $1 不存在！
        echo file $1 not exist!
        echo $2
        exit 1
    fi
}

#清空已存在目录
function checkDiction() {
    #目录清空
    if [ -d $1 ]; then
        rm -rf $1
    fi
    mkdir -p $1

    #将文件移动至文件夹
    for i in "$@"; do
        if [ "${i}" = "$1" ]; then
            continue
        fi

        cp ${i} $1
    done
}

path=""                              #工具路径
channelID="mychannel"                #通道名
crypto_config="./crypto-config.yaml" #crypto-config.yaml 文件位置
configtx="./configtx.yaml"           #configtx.yaml 文件位置
orderer="./orderer.yaml"             #orderer.yaml 文件位置
ports_config="./ports.config"        #ports.config 文件位置
port="7050"                          #order端口

if [ 0"${GOPATH}" != "0" ]; then
    path="${GOPATH}/src/github.com/hyperledger/fabric/fabric-samples/bin/"
fi

while [[ $# -ge 1 ]]; do
    key="$1"
    case $key in
    -h)
        printHelp
        exit 0
        ;;
    -clear)
        path=""
        channelID=""
        crypto_config=""
        configtx=""
        orderer=""
        ;;
    -Path)
        path="$2"
        shift
        ;;
    -channelID)
        channelID="$2"
        shift
        ;;
    -crypto_config)
        crypto_config="$2"
        shift
        ;;
    -configtx)
        configtx="$2"
        shift
        ;;
    -orderer)
        orderer="$2"
        shift
        ;;
    -ports_config)
        ports_config="$2"
        shift
        ;;
    -port)
        port="$2"
        shift
        ;;
    *)
        echo
        echo "Unknown flag: $key"
        echo
        printHelp
        exit 1
        ;;
    esac
    shift
done

#环境变量配置
export PATH=${path}:$PATH

#判断文件是否存在
checkFile $crypto_config "未找到证书文件，无法创建证书"
checkFile $configtx "未找到创世区块配置，无法生成创世区块"
checkFile $orderer "未找到 order 配置文件，无法启动 order"

#判断目录是否存在
checkDiction "./organizations/" $crypto_config
checkDiction "./order/" $configtx $orderer
checkDiction "./organizations/tlscacerts"

#纠正配置文件位置
while [ ! -f ${ports_config} ]; do
    echo "文件 ${ports_config} 不存在！"
    echo "请输入正确的配置文件位置"
    read ports_config
done

#替换端口设置
replaceContent "./order/$configtx" '$order_port' "${port}"
replaceContent "./order/$orderer" '$order_port' "${port}"

for line in $(cat ${ports_config}); do
    temp=$(echo ${line// /} | tr -d '\r')
    temp_array=(${temp//:/ })

    replaceContent "./order/$configtx" '$'${temp_array[0]}'_port' "${temp_array[1]}"
done

#创建证书
cryptogen generate --config=./organizations/crypto-config.yaml --output ./organizations/
checkRet $?

#生成系统创始区块
configtxgen -configPath ./order/ -profile OrdererGenesis -channelID system-channel -outputBlock ./order/system-genesis-block/genesis.block
checkRet $?

#创建通道创建事务
configtxgen -configPath ./order/ -profile Channel -outputCreateChannelTx ./order/channel-artifacts/$channelID.tx -channelID $channelID
checkRet $?

#批量拷贝节点证书
for i in $(ls ./organizations/peerOrganizations -1); do
    for j in $(ls ./organizations/peerOrganizations/$i/peers -1); do
        for line in $(cat ${ports_config}); do
            temp=$(echo ${line// /} | tr -d '\r')
            if [ "$(awk 'BEGIN{print match("'${temp}'","'${j}'")}')" != "0" ]; then
                cp ./organizations/peerOrganizations/$i/peers/$j/tls/ca.crt ./organizations/tlscacerts/${temp}
                break
            fi
        done
    done
done

cd ./order/
orderer start
checkRet $?
